package doughnut.xc.Demo;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;

/**
 * 待样式的POI导出
 */
public class POIDemo2 {
    public static void main(String[] args) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建工作表
        XSSFSheet sheet = workbook.createSheet("样式POI");
        // 第一行
        XSSFRow row = sheet.createRow(0);
        // 设置列宽
        sheet.setColumnWidth(0,7*256);
        sheet.setColumnWidth(1,10*256);
        sheet.setColumnWidth(2,18*256);
        sheet.setColumnWidth(3,20*256);
        sheet.setColumnWidth(4,30*256);
        // 标题需求：行高：42； 字体：黑体 18； 合并单元格：纵向5列； 对齐方式：水平垂直居中； 边框；全边框
        CellStyle cellStyle  =  workbook.createCellStyle();
        // 边框；全边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        // 居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        for (int i = 0; i < 5; i++) {
            row.createCell(i).setCellStyle(cellStyle);
        }
        // 行高：42
        row.setHeightInPoints(42);
        // 合并单元格：纵向5列
        // int firstRow 起始行, int lastRow 结束行, int firstCol 起始列, int lastCol 结束列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));

        // 字体
        XSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 18);
        // 把字体放入样式中
        cellStyle.setFont(font);

        row.getCell(0).setCellValue("用户数据");

        // 小标题样式 复用
        XSSFCellStyle lititleCellStyle = workbook.createCellStyle();
        lititleCellStyle.cloneStyleFrom(cellStyle);
        // 小标题
        XSSFRow row1 = sheet.createRow(1);
        String[] lititle = new String[]{"编号", "姓名", "手机号", "入职日期", "现住址"};
        XSSFCell cell = null;
        for (int i = 0; i < lititle.length; i++) {
            cell = row1.createCell(i);
            cell.setCellValue(lititle[i]);
            cell.setCellStyle(lititleCellStyle);
        }
        // 小标题字体、行高
        row1.setHeightInPoints(25);
        XSSFFont lititleFont = workbook.createFont();
        lititleFont.setFontName("华文行楷");
        lititleFont.setFontHeightInPoints((short)12);
        lititleCellStyle.setFont(lititleFont);

        FileOutputStream fileOutputStream = new FileOutputStream("d:/test.xlsx");

        workbook.write(fileOutputStream);
        fileOutputStream.close();
        workbook.close();
    }
}
